const sqlite3 = require('sqlite3');
const { open } = require('sqlite');
const bcrypt = require('bcrypt');
const path = require('path');
const fs = require('fs');

let db = null;

const initDb = async () => {
    try {
        // 打开数据库连接
        db = await open({
            filename: path.join(__dirname, 'users.db'),
            driver: sqlite3.Database
        });

        // 创建用户表
        await db.exec(`
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password TEXT NOT NULL,
                root_path TEXT NOT NULL
            )
        `);

        // 检查是否需要插入默认用户
        const count = await db.get('SELECT COUNT(*) as count FROM users');
        if (count.count === 0) {
            // 为默认用户创建目录
            const zsDir = path.join(__dirname, 'uploads', 'zs');
            const lsDir = path.join(__dirname, 'uploads', 'ls');
            
            fs.mkdirSync(zsDir, { recursive: true });
            fs.mkdirSync(lsDir, { recursive: true });

            // 插入默认用户（使用明文密码 'ddd'）
            const password = 'ddd';
            await db.run(
                'INSERT INTO users (username, password, root_path) VALUES (?, ?, ?)',
                ['zs', password, zsDir]
            );
            await db.run(
                'INSERT INTO users (username, password, root_path) VALUES (?, ?, ?)',
                ['ls', password, lsDir]
            );

            console.log('默认用户创建成功');
        }

        console.log('数据库初始化成功');
    } catch (err) {
        console.error('数据库初始化失败:', err);
        process.exit(1);
    }
};

const getDb = () => {
    if (!db) {
        throw new Error('数据库未初始化');
    }
    return db;
};

module.exports = {
    initDb,
    getDb
};